from insts.inst import Index16Instruction
from jthread.frame import JFrame


class CHECK_CAST(Index16Instruction):

    def execute(self, frame: JFrame):
        stack = frame.getOperandStack()
        ref = stack.popRef()
        stack.pushRef(ref)
        if ref is None:
            return
        cp = frame.getJMethod().getKlass().getConstantPool()
        classRef = cp.getConstantValue(self.index)
        klass = classRef.resolveClass()
        if not ref.isInstance(klass):
            raise RuntimeError("java.lang.ClassCastException")
